#include <ESP8266WiFi.h>
/* 依赖 PubSubClient 2.4.0 */
#include <PubSubClient.h>
/* 依赖 ArduinoJson 5.13.4 */
#include <ArduinoJson.h>
//#include <SparkFun_SHTC3.h>
#include <string.h>

/* 连接您的WIFI SSID和密码 */
#ifndef CLIENT
#define WIFI_SSID         "Hello"
#define WIFI_PASSWD       "helloworld"
#else
#define WIFI_SSID         "songjie_iPhone"
#define WIFI_PASSWD       "1473238439"
#endif



/* 设备的三元组信息*/
#define PRODUCT_KEY       "a1p7vHHvICz"
#define DEVICE_NAME       "ArduinoCar"
#define DEVICE_SECRET     "0d4fedcabcd36614a3751a563552b78a"
#define REGION_ID         "cn-shanghai"

/* 线上环境域名和端口号，不需要改 */
#define MQTT_SERVER       PRODUCT_KEY ".iot-as-mqtt." REGION_ID ".aliyuncs.com"
#define MQTT_PORT         1883
#define MQTT_USRNAME      DEVICE_NAME "&" PRODUCT_KEY

#define CLIENT_ID         "ArduinoCar|securemode=2,signmethod=hmacsha1|"
// 算法工具: http://iot-face.oss-cn-shanghai.aliyuncs.com/tools.htm 进行加密生成password
// password教程 https://www.yuque.com/cloud-dev/iot-tech/mebm5g
#define MQTT_PASSWD       "31B46C3460DFBF65F02DE802605709D2AFCBBD61"

#define ALINK_BODY_FORMAT         "{\"id\":\"ESP8266\",\"version\":\"1.0\",\"method\":\"thing.event.property.post\",\"params\":%s}"
#define ALINK_TOPIC_PROP_POST     "/sys/" PRODUCT_KEY "/" DEVICE_NAME "/thing/event/property/post"

unsigned long lastMs = 0;

WiFiClient espClient;
PubSubClient  client(espClient);
StaticJsonDocument<200> doc;

void callback(char *topic, byte *payload, unsigned int length)
{
//    Serial.print("Message arrived [");
//    Serial.print(topic);
//    Serial.print("] ");
//    payload[length] = '\0';
//    Serial.println((char *)payload);

      DeserializationError err = deserializeJson(doc, payload);
      // Parse succeeded?
      if (err) {
        Serial.print(F("deserializeJson() returned "));
      }
      char output[256];
      StaticJsonDocument<64> params;
      params = doc["params"];
      serializeJson(params, output);
      Serial.print(output);
}

void wifiInit()
{
    WiFi.mode(WIFI_STA);
    WiFi.begin(WIFI_SSID, WIFI_PASSWD);   //连接WiFi
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.println("WiFi not Connect");
    }
    Serial.println("Connected to AP");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());    
    Serial.print("espClient [");
    client.setServer(MQTT_SERVER, MQTT_PORT);   /* 连接WiFi之后，连接MQTT服务器 */
    client.setCallback(callback);
}


void mqttCheckConnect()
{
    while (!client.connected())
    {
        Serial.println("Connecting to MQTT Server ...");
        if (client.connect(CLIENT_ID, MQTT_USRNAME, MQTT_PASSWD))

        {

            Serial.println("MQTT Connected!");

        }
        else
        {
            Serial.print("MQTT Connect err:");
            Serial.println(client.state());
            delay(5000);
        }
    }
}


void mqttIntervalPost()
{
    char rxBuf[128] = {0};
    char *param;
    char jsonBuf[256];
    int i = 1;
    while (Serial.available() > 0) {
      if (Serial.read() == '{') {
        rxBuf[0] = '{';
        break;
      }
    }
    while (Serial.available() > 0 && i < 127) {
      rxBuf[i] = Serial.read();
      if (rxBuf[i] == '}') {
          rxBuf[i + 1] = 0;
          break;
      }
      i++;
    }
    //param = strstr((char *)rxBuf, "{");
    sprintf(jsonBuf, ALINK_BODY_FORMAT, rxBuf);
    Serial.println(jsonBuf);
    boolean d = client.publish(ALINK_TOPIC_PROP_POST, jsonBuf);
    if(d){
      Serial.println("publish success"); 
    }else{
      Serial.println("publish fail"); 
    }
}

void setup() 
{
    /* initialize serial for debugging */
    Serial.begin(115200);
    wifiInit();
}


// the loop function runs over and over again forever
void loop()
{
  delay(500);                  //延时500毫秒

  if (millis() - lastMs >= 30000)
  {
    lastMs = millis();
    mqttCheckConnect(); 

    /* 上报 */
    mqttIntervalPost();
  }
  client.loop();
}
